#!/usr/bin/env python

from pyserver import pyinit_server

import os, sys, getopt, logging, signal
from ConfigParser import SafeConfigParser

PACKAGE_NAME = 'pyserver'
PACKAGE_VERSION = '0.1'

def print_version ():
    print ("%s version %s\n" % (PACKAGE_NAME, PACKAGE_VERSION)),
    print ("Copyright (C) 2013 Philip Herron\n"),
    print ("Doom comes with ABSOLUTELY NO WARRANTY.\n"),
    print ("You may do whatever you like with the code...\n"),

def print_help (arg):
    print ("Usage: %s [option-or-filename]...\n" % arg),
    print ("\n -h Print this help\n"),
    print (" -v Print the version\n"),
    print (" -c <file> Use specified config\n"),
    print (" -l <file> Use specified log file\n"),
    print (" -d Logger verbose with debug\n"),
    print (" -F Fork me\n\n"),

def messageServer ():
    try:
        opts, args = getopt.getopt (sys.argv[1:], "Fdhvc:l:")
    except getopt.GetoptError as err:
        print str (err)
        print_help (sys.argv[0])
        sys.exit (1)
    logfile = None
    conf = None
    verbose = False
    forkme = False
    for o, a in opts:
        if o == "-v":
            print_version ()
            sys.exit (0)
        elif o in ("-h"):
            print_help (sys.argv[0])
            sys.exit (0)
        elif o in ("-c"):
            conf = a
        elif o in ("-F"):
            forkme = True
        elif o in ("-d"):
            verbose = True
        elif o in ("-l"):
            logfile = a
        else:
            assert False, "unhandled option"
    # make sure we got required arguments
    if not logfile or not conf:
        print >> sys.stderr, "No log or config file"
        print_help (sys.argv[0])
        sys.exit (1)
    parser = SafeConfigParser ()
    parser.read (conf)
    # fork to properly background the process
    if forkme:
        pid = os.fork ()
        if pid == -1:
            print >> sys.stderr, "ERROR: some kind of error forking!"
            sys.exit (1)
        elif pid == 0:
            pass
        else:
            print pid
            sys.exit (0)
    # setup logger
    if verbose:
        logging.basicConfig (filename = logfile,
                             level = logging.DEBUG,
                             format = '%(levelname)s %(asctime)s: %(message)s',
                             datefmt = '%m/%d/%Y %I:%M:%S',
                             filemode = 'w')
    else:
        logging.basicConfig (filename = logfile,
                             level = logging.INFO,
                             format = '%(levelname)s %(asctime)s: %(message)s',
                             datefmt = '%m/%d/%Y %I:%M:%S',
                             filemode = 'w')
    logging.info ("trying to start server...")
    pyinit_server (int (parser.get ("pyserver", "port")))
    print "done..."

if __name__ == "__main__":
    messageServer ()
